package settings.action;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import settings.json.UpdateTableSettingJson;
import settings.service.TableManager;
import common.action.BaseAction;

public class SaveTablesAction extends BaseAction {

	private static final long serialVersionUID = -5251623348898103594L;
	private ObjectMapper jsonMapper;
	private TableManager tableManager;
	
	public String execute() throws Exception
	{
		HttpServletRequest request = ServletActionContext.getRequest();
		UpdateTableSettingJson updateTableSettingJson = null;
		try {
			updateTableSettingJson = jsonMapper.readValue(request.getInputStream(), UpdateTableSettingJson.class);
		} 
		catch (JsonParseException e1) {
			e1.printStackTrace();
		} 
		catch (JsonMappingException e1) {
			e1.printStackTrace();
		} 
		catch (IOException e1) {
			e1.printStackTrace();
		}
		 
		Integer tableId = updateTableSettingJson.getId();
		if(tableId == null)
		{
			tableManager.addTable(updateTableSettingJson.getNumber(), updateTableSettingJson.getMaxPersons(),
				  	  			  updateTableSettingJson.getStatus(), updateTableSettingJson.getType());
		}
		else
		{
			tableManager.updateTable(updateTableSettingJson.getId(), updateTableSettingJson.getNumber(), 
			         updateTableSettingJson.getMaxPersons(), updateTableSettingJson.getStatus(),
			         updateTableSettingJson.getType());		
		}
		
		Map<String, String> resMap = new HashMap<String, String>();
		resMap.put("status", "ok");
		String res = null;
		try
		{
			res = jsonMapper.writeValueAsString(resMap);
		}
		catch (RuntimeException e)
		{
			
		} catch (JsonGenerationException e) {
			
			e.printStackTrace();
		} catch (JsonMappingException e) {
			
			e.printStackTrace();
		} catch (IOException e) {
			
			e.printStackTrace();
		}
		
		try
		{
			this.sendClientJSON(res);
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		
		return null;
		
	}

	public ObjectMapper getJsonMapper() {
		return jsonMapper;
	}

	public void setJsonMapper(ObjectMapper jsonMapper) {
		this.jsonMapper = jsonMapper;
	}

	public TableManager getTableManager() {
		return tableManager;
	}

	public void setTableManager(TableManager tableManager) {
		this.tableManager = tableManager;
	}
}
